<template>
  <div class="batch-management">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="searchForm" inline>
        <el-form-item label="货品名称">
          <el-input
            v-model="searchForm.goodsName"
            placeholder="请输入货品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-input
            v-model="searchForm.goodsType"
            placeholder="请输入货品类型"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="单位">
          <el-input
            v-model="searchForm.unit"
            placeholder="请输入单位"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="批次">
          <el-input
            v-model="searchForm.batch"
            placeholder="请输入批次"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-input
            v-model="searchForm.warehouseName"
            placeholder="请输入仓库名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="生产日期">
          <el-date-picker
            v-model="searchForm.productionDate"
            type="date"
            placeholder="选择生产日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="到期日期">
          <el-date-picker
            v-model="searchForm.expirationDate"
            type="date"
            placeholder="选择到期日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button @click="handleExport">导出</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="handleTestData" type="success">测试显示数据</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <!-- 调试信息 -->
      <div v-if="tableData.length === 0 && !loading" class="debug-info">
        <h3>调试信息</h3>
        <p>表格数据长度: {{ tableData.length }}</p>
        <p>分页总数: {{ pagination.total }}</p>
        <p>加载状态: {{ loading }}</p>
        <details>
          <summary>查看 tableData 内容</summary>
          <pre>{{ JSON.stringify(tableData, null, 2) }}</pre>
        </details>
      </div>
      
      <el-table 
        :data="tableData" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="serialNumber" label="序号" width="80" align="center" />
        <el-table-column prop="goodsCode" label="货品编号" show-overflow-tooltip />
        <el-table-column prop="goodsName" label="货品名称" show-overflow-tooltip />
        <el-table-column prop="goodsType" label="货品类型" show-overflow-tooltip />
        <el-table-column prop="specs" label="规格型号" show-overflow-tooltip />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="warehouseName" label="仓库名称" show-overflow-tooltip />
        <el-table-column prop="currentStock" label="当前库存" width="100" align="center" />
        <el-table-column prop="batch" label="批次" show-overflow-tooltip />
        <el-table-column prop="productionDate" label="生产日期" width="120" align="center" />
        <el-table-column prop="expirationDate" label="到期日期" width="120" align="center" />
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBatchPage, exportBatch, getBatchDetail } from '/@/api/batch/batch'

// 搜索表单
const searchForm = reactive({
  goodsName: '',
  goodsType: '',
  unit: '',
  batch: '',
  warehouseName: '',
  productionDate: '',
  expirationDate: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 模拟数据
const mockData = [
  {
    id: 1,
    serialNumber: 1,
    goodsCode: 'HPOH6804',
    goodsName: '苹果手机-1',
    goodsType: '电子产品',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 2,
    serialNumber: 2,
    goodsCode: 'HPOH1795',
    goodsName: '电视机-2',
    goodsType: '家电',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 3,
    serialNumber: 3,
    goodsCode: 'HPOH3705',
    goodsName: '咖啡机-3',
    goodsType: '家电',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 4,
    serialNumber: 4,
    goodsCode: 'HPOH1234',
    goodsName: '空调-4',
    goodsType: '家电',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 5,
    serialNumber: 5,
    goodsCode: 'HPOH5678',
    goodsName: '洗衣机-5',
    goodsType: '家电',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 6,
    serialNumber: 6,
    goodsCode: 'HPOH9012',
    goodsName: '电脑-6',
    goodsType: '电子产品',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 7,
    serialNumber: 7,
    goodsCode: 'HPOH3456',
    goodsName: '手表-7',
    goodsType: '电子产品',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 8,
    serialNumber: 8,
    goodsCode: 'HPOH7890',
    goodsName: '钢笔-8',
    goodsType: '电子产品',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 9,
    serialNumber: 9,
    goodsCode: 'HPOH2468',
    goodsName: '餐具套装-9',
    goodsType: '家电',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 10,
    serialNumber: 10,
    goodsCode: 'HPOH1357',
    goodsName: '运动鞋-10',
    goodsType: '服装',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  },
  {
    id: 11,
    serialNumber: 11,
    goodsCode: 'HPOH9753',
    goodsName: '蓝牙耳机-11',
    goodsType: '电子产品',
    specs: 'red 红色的',
    unit: '个',
    warehouseName: '货品仓库一',
    currentStock: 50,
    batch: '0005454',
    productionDate: '2025-10-27',
    expirationDate: '2025-10-27'
  }
]

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    console.log('开始加载数据...')
    console.log('分页参数:', {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    })
    
    // 调用真实的后端API
    const response = await getBatchPage({
      page: pagination.page,
      pageSize: pagination.pageSize,
      goodsName: searchForm.goodsName,
      goodsType: searchForm.goodsType,
      unit: searchForm.unit,
      batch: searchForm.batch,
      warehouseName: searchForm.warehouseName,
      productionDateStart: searchForm.productionDate ? new Date(searchForm.productionDate) : null,
      productionDateEnd: searchForm.productionDate ? new Date(searchForm.productionDate) : null,
      expirationDateStart: searchForm.expirationDate ? new Date(searchForm.expirationDate) : null,
      expirationDateEnd: searchForm.expirationDate ? new Date(searchForm.expirationDate) : null
    })
    
    console.log('API响应完整对象:', response)
    console.log('API响应类型:', typeof response)
    console.log('API响应数据结构:', Object.keys(response || {}))
    
    // 详细调试信息
    if (response) {
      console.log('response.data:', response.data)
      console.log('response.data类型:', typeof response.data)
      if (response.data) {
        console.log('response.data的键:', Object.keys(response.data))
        console.log('response.data.items:', response.data.items)
        console.log('response.data.total:', response.data.total)
        console.log('response.data.page:', response.data.page)
        console.log('response.data.pageSize:', response.data.pageSize)
      }
    }
    
    // 根据控制台观察，数据在 result.items 中
    let actualData = null
    
    if (response && response.data) {
      // response是完整的axios响应对象，数据在response.data中
      actualData = response.data
      console.log('从response.data中提取数据:', actualData)
    } else if (response && response.result) {
      // 数据可能在response.result中
      actualData = response.result
      console.log('从response.result中提取数据:', actualData)
    } else {
      // 没有data或result属性，直接使用response
      actualData = response
      console.log('直接使用response作为数据:', actualData)
    }
    
    // 处理实际数据 - 优先检查 result.items
    if (actualData && actualData.result && actualData.result.items) {
      // 数据在 result.items 中
      tableData.value = actualData.result.items
      pagination.total = actualData.result.total
      console.log('✅ 使用result.items结构 - 数据项数:', tableData.value.length, '总数:', pagination.total)
    } else if (actualData && actualData.items) {
      // SqlSugarPagedList结构 - 直接包含items和total
      tableData.value = actualData.items
      pagination.total = actualData.total
      console.log('✅ 使用SqlSugarPagedList结构 - 数据项数:', tableData.value.length, '总数:', pagination.total)
    } else if (Array.isArray(actualData)) {
      // 直接返回数组
      tableData.value = actualData
      pagination.total = actualData.length
      console.log('✅ 使用数组结构 - 数据项数:', tableData.value.length)
    } else if (actualData) {
      // 尝试其他可能的结构
      console.warn('⚠️ 未识别的数据结构:', actualData)
      console.log('actualData的键:', Object.keys(actualData))
      
      // 尝试强制提取数据
      if (actualData.data && actualData.data.items) {
        tableData.value = actualData.data.items
        pagination.total = actualData.data.total
        console.log('✅ 强制提取 actualData.data.items - 数据项数:', tableData.value.length)
      } else {
        tableData.value = []
        pagination.total = 0
      }
    } else {
      // 如果API调用失败，使用模拟数据作为降级方案
      console.warn('⚠️ API返回为空，使用模拟数据')
      tableData.value = mockData
      pagination.total = 100
    }
    
    console.log('最终设置结果:', {
      tableDataLength: tableData.value.length,
      paginationTotal: pagination.total,
      firstItem: tableData.value[0]
    })
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，使用模拟数据')
    // 使用模拟数据作为降级方案
    tableData.value = mockData
    pagination.total = 100
  } finally {
    loading.value = false
  }
}

// 测试显示数据
const handleTestData = () => {
  console.log('测试显示数据 - 设置模拟数据')
  tableData.value = mockData
  pagination.total = mockData.length
  console.log('测试数据设置完成:', {
    tableDataLength: tableData.value.length,
    paginationTotal: pagination.total,
    firstItem: tableData.value[0]
  })
}

// 刷新
const handleRefresh = () => {
  loadData()
}

// 导出
const handleExport = async () => {
  try {
    ElMessageBox.confirm('确定要导出批次信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const response = await exportBatch({
        page: pagination.page,
        pageSize: pagination.pageSize,
        ...searchForm
      })
      
      // 创建下载链接
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `批次信息_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      ElMessage.success('导出成功')
    })
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 查看详情
const handleView = async (row: any) => {
  try {
    const response = await getBatchDetail(row.id)
    ElMessageBox.alert(JSON.stringify(response.data, null, 2), '批次详情', {
      confirmButtonText: '确定'
    })
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    goodsName: '',
    goodsType: '',
    unit: '',
    batch: '',
    warehouseName: '',
    productionDate: '',
    expirationDate: ''
  })
  pagination.page = 1
  loadData()
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

// 组件挂载时加载数据
onMounted(() => {
  try {
    loadData()
  } catch (error) {
    console.error('组件挂载时加载数据失败:', error)
  }
})
</script>

<style scoped>
.batch-management {
  padding: 20px;
}

.search-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  margin-bottom: 20px;
}

.action-buttons .el-button {
  margin-right: 10px;
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.debug-info {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.debug-info h3 {
  margin: 0 0 10px 0;
  color: #409eff;
}

.debug-info p {
  margin: 5px 0;
  font-size: 14px;
}

.debug-info details {
  margin-top: 10px;
}

.debug-info pre {
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  max-height: 200px;
}
</style>